<template>
  <div class="text-generation-panel">
    <div class="panel-header">
      <h3 class="panel-title">
        <el-icon><Edit /></el-icon>
        AI文案生成
      </h3>
      <div class="panel-actions">
        <el-button 
          type="primary" 
          :icon="MagicStick"
          :loading="generating"
          @click="handleGenerate"
          :disabled="!selectedImage"
        >
          {{ generating ? '生成中...' : '生成文案' }}
        </el-button>
        <el-button 
          :icon="RefreshRight"
          @click="handleRegenerate"
          :disabled="!hasGeneratedContent || generating"
        >
          重新生成
        </el-button>
      </div>
    </div>
    
    <!-- 生成配置 -->
    <div class="generation-config">
      <div class="config-section">
        <div class="config-title">
          <el-icon><Setting /></el-icon>
          生成配置
        </div>
        
        <div class="config-content">
          <!-- 文案类型选择 -->
          <div class="config-group">
            <label class="config-label">文案类型:</label>
            <el-radio-group v-model="generationConfig.contentType" @change="handleConfigChange">
              <el-radio-button label="SHORT">短句文案</el-radio-button>
              <el-radio-button label="LONG">长句文案</el-radio-button>
            </el-radio-group>
          </div>
          
          <!-- 文案风格选择 -->
          <div class="config-group">
            <label class="config-label">文案风格:</label>
            <el-radio-group v-model="generationConfig.styleType" @change="handleConfigChange">
              <el-radio-button label="PROMOTIONAL">营销推广</el-radio-button>
              <el-radio-button label="WARM">温馨暖心</el-radio-button>
              <el-radio-button label="PROFESSIONAL">专业正式</el-radio-button>
            </el-radio-group>
          </div>
          
          <!-- 自定义提示词 -->
          <div class="config-group">
            <label class="config-label">自定义提示词:</label>
            <el-input
              v-model="generationConfig.customPrompt"
              type="textarea"
              :rows="3"
              placeholder="可选：输入自定义提示词来指导AI生成特定风格的文案..."
              @input="handleConfigChange"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 生成结果 -->
    <div class="generation-results" v-if="generatedTexts.length > 0">
      <div class="results-header">
        <div class="results-title">
          <el-icon><DocumentCopy /></el-icon>
          生成结果 ({{ generatedTexts.length }})
        </div>
        <div class="results-actions">
          <el-button 
            text 
            size="small"
            @click="clearAllResults"
          >
            清空所有
          </el-button>
        </div>
      </div>
      
      <div class="results-list">
        <div
          v-for="(text, index) in generatedTexts"
          :key="text.id || index"
          class="result-item"
          :class="{ 'selected': selectedTextIndex === index }"
        >
          <div class="result-header">
            <div class="result-meta">
              <el-tag 
                :type="getContentTypeTagType(text.contentType)"
                size="small"
              >
                {{ getContentTypeText(text.contentType) }}
              </el-tag>
              <el-tag 
                :type="getStyleTypeTagType(text.styleType)"
                size="small"
              >
                {{ getStyleTypeText(text.styleType) }}
              </el-tag>
              <span class="result-time">{{ formatTime(text.createdAt) }}</span>
            </div>
            
            <div class="result-actions">
              <el-button 
                type="primary" 
                :icon="Select"
                size="small"
                @click="selectText(index)"
                v-if="selectedTextIndex !== index"
              >
                选择
              </el-button>
              <el-button 
                type="success" 
                :icon="Check"
                size="small"
                disabled
                v-else
              >
                已选择
              </el-button>
              <el-button 
                type="info" 
                :icon="CopyDocument"
                size="small"
                @click="copyText(text.content)"
              >
                复制
              </el-button>
              <el-button 
                type="danger" 
                :icon="Delete"
                size="small"
                @click="deleteText(index)"
              >
                删除
              </el-button>
            </div>
          </div>
          
          <div class="result-content">
            <el-input
              v-model="text.content"
              type="textarea"
              :rows="getTextareaRows(text.contentType)"
              @input="handleTextEdit(index, $event)"
              @blur="saveTextEdit(index)"
            />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else class="empty-results">
      <el-icon size="48" color="rgba(255,255,255,0.5)"><Document /></el-icon>
      <h3>暂无生成结果</h3>
      <p>选择图片并点击"生成文案"开始创作</p>
    </div>
    
    <!-- 生成历史 -->
    <div class="generation-history" v-if="historyTexts.length > 0">
      <div class="history-header">
        <div class="history-title">
          <el-icon><Clock /></el-icon>
          历史记录 ({{ historyTexts.length }})
        </div>
        <el-button 
          text 
          size="small"
          @click="loadMoreHistory"
          v-if="hasMoreHistory"
        >
          加载更多
        </el-button>
      </div>
      
      <div class="history-list">
        <div
          v-for="text in historyTexts"
          :key="text.id"
          class="history-item"
          @click="useHistoryText(text)"
        >
          <div class="history-meta">
            <el-tag :type="getContentTypeTagType(text.contentType)" size="small">
              {{ getContentTypeText(text.contentType) }}
            </el-tag>
            <el-tag :type="getStyleTypeTagType(text.styleType)" size="small">
              {{ getStyleTypeText(text.styleType) }}
            </el-tag>
            <span class="history-time">{{ formatTime(text.createdAt) }}</span>
          </div>
          <div class="history-content">
            {{ text.content.substring(0, 100) }}{{ text.content.length > 100 ? '...' : '' }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Edit, MagicStick, RefreshRight, Setting, DocumentCopy, Select, Check,
  CopyDocument, Delete, Document, Clock
} from '@element-plus/icons-vue'
import type { 
  ImageModel, 
  TextContentModel, 
  TextGenerationRequest 
} from '@/types'
import { formatTime, copyToClipboard } from '@/utils'

interface Props {
  selectedImage?: ImageModel
  loading?: boolean
}

interface Emits {
  (e: 'generate', config: TextGenerationRequest): void
  (e: 'regenerate', config: TextGenerationRequest): void
  (e: 'select-text', text: TextContentModel, index: number): void
  (e: 'edit-text', text: TextContentModel, index: number): void
  (e: 'delete-text', text: TextContentModel, index: number): void
  (e: 'load-history', imageId: number): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const generating = ref(false)
const selectedTextIndex = ref(-1)
const generatedTexts = ref<TextContentModel[]>([])
const historyTexts = ref<TextContentModel[]>([])
const hasMoreHistory = ref(false)

const generationConfig = ref<TextGenerationRequest>({
  imageId: 0,
  contentType: 'SHORT',
  styleType: 'PROMOTIONAL',
  customPrompt: ''
})

// 计算属性
const hasGeneratedContent = computed(() => generatedTexts.value.length > 0)

// 监听选中图片变化
watch(() => props.selectedImage, (newImage) => {
  if (newImage) {
    generationConfig.value.imageId = newImage.id
    loadHistory()
  }
}, { immediate: true })

// 方法
const handleGenerate = () => {
  if (!props.selectedImage) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  generating.value = true
  emit('generate', { ...generationConfig.value })
}

const handleRegenerate = () => {
  if (!props.selectedImage) {
    ElMessage.warning('请先选择图片')
    return
  }
  
  generating.value = true
  emit('regenerate', { ...generationConfig.value })
}

const handleConfigChange = () => {
  // 配置变化时的处理
}

const selectText = (index: number) => {
  selectedTextIndex.value = index
  emit('select-text', generatedTexts.value[index], index)
}

const copyText = async (content: string) => {
  try {
    await copyToClipboard(content)
    ElMessage.success('文案已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const deleteText = (index: number) => {
  const text = generatedTexts.value[index]
  generatedTexts.value.splice(index, 1)
  
  // 调整选中索引
  if (selectedTextIndex.value === index) {
    selectedTextIndex.value = -1
  } else if (selectedTextIndex.value > index) {
    selectedTextIndex.value--
  }
  
  emit('delete-text', text, index)
}

const handleTextEdit = (index: number, content: string) => {
  generatedTexts.value[index].content = content
}

const saveTextEdit = (index: number) => {
  const text = generatedTexts.value[index]
  emit('edit-text', text, index)
}

const clearAllResults = () => {
  generatedTexts.value = []
  selectedTextIndex.value = -1
}

const loadHistory = () => {
  if (props.selectedImage) {
    emit('load-history', props.selectedImage.id)
  }
}

const loadMoreHistory = () => {
  // 加载更多历史记录
}

const useHistoryText = (text: TextContentModel) => {
  // 将历史文案添加到当前结果中
  generatedTexts.value.unshift({ ...text })
  ElMessage.success('已添加历史文案到当前结果')
}

const getContentTypeText = (type: string) => {
  switch (type) {
    case 'SHORT': return '短句'
    case 'LONG': return '长句'
    default: return type
  }
}

const getContentTypeTagType = (type: string) => {
  switch (type) {
    case 'SHORT': return 'success'
    case 'LONG': return 'primary'
    default: return ''
  }
}

const getStyleTypeText = (type: string) => {
  switch (type) {
    case 'PROMOTIONAL': return '营销'
    case 'WARM': return '温馨'
    case 'PROFESSIONAL': return '专业'
    default: return type
  }
}

const getStyleTypeTagType = (type: string) => {
  switch (type) {
    case 'PROMOTIONAL': return 'danger'
    case 'WARM': return 'warning'
    case 'PROFESSIONAL': return 'info'
    default: return ''
  }
}

const getTextareaRows = (type: string) => {
  return type === 'LONG' ? 6 : 3
}

// 暴露方法给父组件
defineExpose({
  addGeneratedText: (text: TextContentModel) => {
    generatedTexts.value.unshift(text)
    generating.value = false
  },
  setHistoryTexts: (texts: TextContentModel[]) => {
    historyTexts.value = texts
  },
  setGenerating: (status: boolean) => {
    generating.value = status
  },
  getSelectedText: () => {
    return selectedTextIndex.value >= 0 ? generatedTexts.value[selectedTextIndex.value] : null
  }
})
</script>

<style scoped>
.text-generation-panel {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  color: white;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.panel-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.panel-actions {
  display: flex;
  gap: 10px;
}

/* 生成配置样式 */
.generation-config {
  margin-bottom: 30px;
}

.config-section {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 20px;
}

.config-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 20px;
  color: rgba(255, 255, 255, 0.9);
}

.config-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.config-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.config-label {
  font-size: 14px;
  font-weight: 500;
  color: rgba(255, 255, 255, 0.8);
}

/* 生成结果样式 */
.generation-results {
  margin-bottom: 30px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.results-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.result-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 20px;
  transition: all 0.3s ease;
}

.result-item.selected {
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid rgba(64, 158, 255, 0.3);
}

.result-item:hover {
  background: rgba(255, 255, 255, 0.08);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.result-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

.result-actions {
  display: flex;
  gap: 8px;
}

.result-content {
  width: 100%;
}

.result-content :deep(.el-textarea__inner) {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
  color: white;
  border-radius: 8px;
}

.result-content :deep(.el-textarea__inner):focus {
  border-color: #409EFF;
}

/* 空状态样式 */
.empty-results {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.7);
}

.empty-results h3 {
  margin: 20px 0 10px 0;
  color: white;
}

/* 历史记录样式 */
.generation-history {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 20px;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.history-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.history-item:hover {
  background: rgba(255, 255, 255, 0.1);
  transform: translateX(5px);
}

.history-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.history-time {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.6);
}

.history-content {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  line-height: 1.4;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .text-generation-panel {
    padding: 15px;
  }
  
  .panel-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .panel-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .config-group {
    gap: 8px;
  }
  
  .result-header {
    flex-direction: column;
    gap: 10px;
  }
  
  .result-actions {
    width: 100%;
    justify-content: space-between;
  }
}
</style>